
#include "main.h"
#include     <stdio.h>      /*标准输入输出定义*/
#include     <stdlib.h>     /*标准函数库定义*/
#include     <unistd.h>     /*Unix 标准函数定义*/
#include     <sys/types.h>
#include     <sys/stat.h>
#include     <fcntl.h>      /*文件控制定义*/

 int fd,num;
 data_acquisition::data_acquisition(QObject *parent) :
    QThread(parent)
{
    first[0]=1;
    first[1]=1;
    count[1]=0;
    count[2]=0;

}
void data_acquisition::run()
{
    fd=open("/dev/adc", O_RDWR);
     if(fd==-1) { close(fd); printf("open adc failure \n");}
     else
    while (1)
    {
       read_value(11);
       convert(11,170);
       msleep(100);
    }
}


void data_acquisition::read_value(int m)
{
  unsigned char i;
 // t=250/m;
 ioctl(fd, ADC_INPUT_PIN,2);
      for(i=0;i<m;i++)
    {
      read(fd,&num,sizeof(int));
       adc_temperature_value[i]=num; //msleep(t);
     }
 ioctl(fd, ADC_INPUT_PIN,3);
      for(i=0;i<m;i++)
    {
      read(fd,&num,sizeof(int));
      adc_pressure_value[i]=num;// msleep(t);
     }
}



void data_acquisition::QP(int A[],int n)  //优化的冒泡排序
{
    int t,flag;
    for(int i=0;i<n-1;i++)
    {
        flag=0;
        for(int j=0;j<n-i;j++)
        {
            if(A[j+1]<A[j])
            {
                t=A[j];
                A[j]=A[j+1];
                A[j+1]=t;
                flag=1;
            }
        }
        if(flag==0) break;
    }
}

template <typename T>
inline void  data_acquisition::linear(T& m,T value,T n,int i)//
{
   T buf=m-value;
   if(buf< 0)  buf=0 - buf;
   if(first[i]) { m=value;first[i]=0;}
   else { if(buf<= n)  {m=value;count[i]=0; }
          else  {count[i]++; if(count[i]==2) {m=value;count[i]=0;} }
        }
}

void data_acquisition::convert(int m,int R)
{
      QP(adc_temperature_value,m);
      QP(adc_pressure_value,m);
      int mid=(m-1)/2;
     TEM_buf=(float)((adc_temperature_value[mid]*10.0708)/R-100);
     PSU_buf=(adc_pressure_value[mid]*20.1416)/R-200;

     if(PSU_buf>20) PSU_buf+=positive_pressure_adjust;
     else if(PSU_buf<-20)  PSU_buf+=negative_pressure_adjust;
     else PSU_buf+=normal_pressure_adjust;
     TEM_buf+=temperature_adjust*0.1;
   //  PSU=PSU_buf;
   //  TEM=TEM_buf;
   linear(PSU,PSU_buf,2,0);
   linear(TEM,TEM_buf,(float)0.3,1);
}

























